package asms;

import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.commons.AdviceAdapter;

public class ProcessBuilderVisitor extends ClassVisitor implements Opcodes {
    public ProcessBuilderVisitor(ClassVisitor classVisitor) {
        super(ASM5, classVisitor);
    }

    public ProcessBuilderVisitor(int api, ClassVisitor classVisitor) {
        super(api, classVisitor);
    }
    @Override
    public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
        MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);

        if ("start".equals(name) && "()Ljava/lang/Process;".equals(desc)) {
            System.out.println("MethodName is: " + name + ", access is: "+ access
                    + ", descriptor is: "+desc+ ", signature is: "+signature+", exceptions is: "+exceptions);
            return new AdviceAdapter(Opcodes.ASM5, mv, access, name, desc) {
                @Override
                public void visitCode() {

                    mv.visitVarInsn(ALOAD, 0);
                    mv.visitFieldInsn(GETFIELD, "java/lang/ProcessBuilder", "command", "Ljava/util/List;");
                    mv.visitMethodInsn(INVOKESTATIC, "hook/ProcessBuilderHook", "handler", "(Ljava/util/List;)V", false);

                    super.visitCode();
                }
            };
        }
        return mv;
    }

    /**
     * 扫描到属性的时候会自动调用该方法。
     * 这里我们打印属性信息.
     */
    @Override
    public FieldVisitor visitField(int access, String name, String descriptor, String signature, Object value) {
        FieldVisitor fieldVisitor = super.visitField(access, name, descriptor, signature, value);
        System.out.println("FieldName is: " + name + ", access is: " + access + ", signature is: " + signature + ", descriptor is: " + descriptor + ". value is: " + value);

        return fieldVisitor;
    }
}
